<template>
  <view class="main">
    <view class="title"> 登录 </view>
    <view class="form">
      <view class="form-item">
        <input type="number" maxlength="11" placeholder="输入手机号" v-model="codeFromData.phonenumber" />
      </view>
      <!-- v-if="!isScan" -->
      <view class="form-item code-box" v-if="!isScan">
        <input type="number" maxlength="6" placeholder="输入验证码" v-model="codeFromData.code" />
        <view class="code" v-if="show" @click="getCode">获取验证码</view>
        <view class="code" v-else>{{ count }}s</view>
      </view>
    </view>
    <view class="login-btn">
      <Button @clickButton="postLogin" :loading="loading" loading-text="登录中" text="登录" />
    </view>
    <view class="proxy dispaly-center">
      <van-checkbox checked-color="#0753fd" v-model="checked"></van-checkbox>
      <view class="proxy-text txt" @click="checked = !checked">已阅读并同意</view>
      <view class="proxy-text user" @click="$goUrl(`/pages/login/proxy`)">《用户协议》</view>
      <view> 和 </view>
      <view class="proxy-text user" @click="$goUrl(`/pages/login/userTready`)">《隐私政策》</view>
    </view>

    <!--<view class="more-login dispaly-col-center" @click="wxLog">
      <view class="more-login-text">快捷登录</view>
      <view class="w-logo">
        <image src="/static/icon/weChat.svg" mode="aspectFill" />
      </view>
    </view>  -->
  </view>
</template>

<script setup>
import {
  debounce,
  isWechat,
  checkWeChatCode,
  getWeChatCode,
  deleteObjectEmptyKey,
} from "@/utils/util";
import { ref } from "vue";
import { login, getUserInfo, getSmsCode, getOpenId } from "@/api/apiList";
import { onLoad } from "@dcloudio/uni-app";

const isWeixin = ref(false);
const isScan = ref("");
const circleId = ref("");
const userId = ref("");
const checked = ref(true);
const weiCode = ref("");
onLoad((option) => {
  const params = new URLSearchParams(window.location.search);
  const ua = navigator.userAgent.toLowerCase();
  isScan.value = option.type ? option.type : "";
  circleId.value = option.circleId ? option.circleId : "";
  userId.value = option.userId ? option.userId : "";
  isWeixin.value = isWechat();

  if (params && params.get("code")) {
    weiCode.value = params.get("code");
  }

  // if (isWeixin.value && weiCode.value) {
  //   let code = params.get("code");
  //   if (code) {
  //     console.log(code, "code");
  //     wxLogin(code);
  //   }
  // }

  if (isWeixin.value && !params.get("code")) {
    getWeChatLoginCode();
  }
});

const getWeChatLoginCode = () => {
  let redirect_uri = encodeURIComponent(
    "https://h5.qunxinghuzhu.com/h5/#/pages/login/login/"
  );
  let appId = "wx5fcd79543f91406a";
  // 跳转获取登录code
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_wechat_redirect
     `;
};

const getWeChatLoginCodeInfo = () => {
  let redirect_uri = encodeURIComponent(
    "https://h5.qunxinghuzhu.com/h5/#/pages/login/login/"
  );
  let appId = "wx5fcd79543f91406a";
  // 跳转获取登录code
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_wechat_redirect
     `;
};

const wxLog = () => {
  if (!checked.value) {
    uni.showToast({
      title: "请同意用户协议",
      icon: "none",
    });
  } else {
    getWeChatLoginCodeInfo();
  }
};

const wxLogin = async (code) => {
  console.log(code);
  if (code) {
    const res = await login({
      wxCode: code,
    });
    if (res.code == 200) {
      uni.setStorageSync("token", res.msg);
      uni.showToast({
        title: "登录成功",
        icon: "none",
      });
      getUserInfoData();
    }
  }
};

const codeFromData = ref({
  phonenumber: "",
  code: "",
  id: "",
  userId: "",
});

// 获取验证码
const count = ref("");
const show = ref(true);
const timer = ref(null);
let reg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
const code = ref("");
const getCode = debounce(
  async () => {
    if (reg.test(codeFromData.value.phonenumber)) {
      const res = await getSmsCode({
        phonenumber: codeFromData.value.phonenumber,
      });
      code.value = res.msg;
      if (res.code == 200) {
        uni.showToast({
          title: "验证码已发送请注意查收",
          icon: "none",
        });
        const TIME_COUNT = 60;
        if (!timer.value) {
          count.value = TIME_COUNT;
          show.value = false;
          timer.value = setInterval(() => {
            if (count.value > 0 && count.value <= TIME_COUNT) {
              count.value -= 1;
            } else {
              show.value = true;
              clearInterval(timer.value);
              timer.value = null;
            }
          }, 1000);
        }
      }
    } else {
      uni.showToast({
        title: "手机号格式不对",
        icon: "none",
      });
    }
  },
  1000,
  false
);

// 登录
const loading = ref(false);
const postLogin = async () => {
  try {
    if (checked.value) {
      if (isScan.value) {
        if (!codeFromData.value.phonenumber) {
          uni.showToast({
            title: "请输入手机号",
            icon: "none",
          });
          return;
        }
      } else {
        if (!codeFromData.value.phonenumber) {
          uni.showToast({
            title: "请输入手机号",
            icon: "none",
          });
          return;
        }
        if (!codeFromData.value.code) {
          uni.showToast({
            title: "请输入验证码",
            icon: "none",
          });
          return;
        }
        // if (codeFromData.value.code != code.value) {
        //     uni.showToast({
        //         title: '验证码错误',
        //         icon: 'none'
        //     })
        //     return
        // }
      }
      loading.value = true;

      const newFormData = deleteObjectEmptyKey(codeFromData.value);
      const res = await login(newFormData);
      if (res.code == 200) {
        uni.setStorageSync("token", res.msg);
        uni.showToast({
          title: "登录成功",
          icon: "none",
        });
        getUserInfoData();
        loading.value = false;
      } else {
        loading.value = false;
      }
    } else {
      uni.showToast({
        title: "请勾选用户协议",
        icon: "none",
      });
    }
  } catch (e) {
    loading.value = false;
    console.log(e)
  }
};

const getUserInfoData = async () => {
  const res = await getUserInfo();
  if (res.code != 200) {
    // 获取个人信息失败 清除token
    uni.setStorageSync("token", "");
    return uni.showToast({
      title: "获取个人信息失败",
      icon: "none",
    });
  }

  let errM = "";
  if (weiCode.value && !res.data.openId) {
    let result = await getOpenId({ code: weiCode.value });
    if (result.code != 200) {
      errM = result.msg || "绑定openId失败";
    }
  }

  if (errM) {
    return uni.showToast({
      title: errM,
      icon: "none",
    });
  }

  if (res.code == 200) {
    uni.setStorageSync("userInfo", res.data);
    if (uni.getStorageSync("loginBackUrl")) {
      let back = uni.getStorageSync("loginBackUrl");
      uni.setStorageSync("loginBackUrl", "");
      return uni.navigateTo({
        url: back,
      });
    }
    if (isScan.value) {
      setTimeout(() => {
        loading.value = false;
        uni.navigateTo({
          url: `/pages/index/pages/groupDetail?id=${circleId.value}&userId=${userId.value}`,
        });
      }, 1000);
    } else {
      if (res.data.industryId) {
        setTimeout(() => {
          loading.value = false;
          uni.reLaunch({
            url: "/pages/index/index",
          });
        }, 1000);
      } else {
        setTimeout(() => {
          loading.value = false;
          uni.navigateTo({
            url: "/pages/login/selectIndustry",
          });
        }, 1500);
      }
    }
  } else {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.main {
  padding: 0 50rpx;

  .title {
    margin: 100rpx 0 248rpx 0;
    font-family: PingFang SC Heavy;
    font-size: 60rpx;
    font-weight: normal;
    color: #0753fd;
  }

  .form {
    .form-item:first-child {
      margin-bottom: 40rpx;
    }

    .code-box {
      position: relative;

      .code {
        position: absolute;
        right: 60rpx;
        top: 50%;
        transform: translate(0, -50%);
        font-family: PingFang SC Medium;
        font-size: 28rpx;
        font-weight: normal;
        color: #0753fd;
      }
    }

    .form-item {
      height: 108rpx;
      border-radius: 54rpx;
      background: #ffffff;

      input {
        padding: 38rpx 0 38rpx 44rpx;
        border-radius: 54rpx;
        background: #ffffff;
      }
    }
  }

  .login-btn {
    margin-top: 70rpx;
    margin-bottom: 60rpx;
  }

  .proxy {
    .proxy-text {
      font-family: PingFang SC Regular;
      font-size: 28rpx;
      font-weight: normal;
      color: #111111;
    }

    .txt {
      margin-left: 8rpx;
    }

    .user {
      color: #0753fd !important;
    }
  }

  .more-login {
    margin-top: 210rpx;

    .more-login-text {
      margin-bottom: 18rpx;
      font-family: PingFang SC Medium;
      font-size: 24rpx;
      font-weight: normal;
      color: #999999;
    }

    .w-logo {
      image {
        width: 132rpx;
        height: 132rpx;
      }
    }
  }
}
</style>
